using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;

namespace DalatCooking.Core
{
	public class CustomPrincipal: System.Security.Principal.IPrincipal
	{
		protected System.Security.Principal.IIdentity identity;
		protected ArrayList roleList;

		public CustomPrincipal( string email )
		{		
			identity = new CustomIdentity(email);
			roleList = PersonManager.FindAllPersonRoles( ((CustomIdentity)identity).UserID );
		}

		public CustomPrincipal( int userID )
		{	
			identity = new CustomIdentity(userID);
            roleList = PersonManager.FindAllPersonRoles(((CustomIdentity)identity).UserID);
		}

        public static CustomPrincipal ValidateLogin(string email, string password)
        {
            int userID;
            /*
			string connectionString = ConfigurationSettings.AppSettings["ConnectionString"];
			SqlConnection connection = new SqlConnection(connectionString);

			connection.Open();

			SqlCommand command = new SqlCommand("ValidateLogin", connection);
			command.Parameters.Add("@Email", email);
			command.Parameters.Add("@Password", password);
			// add return value parameter
			command.Parameters.Add( new SqlParameter ( "ReturnValue",SqlDbType.Int,4,
				ParameterDirection.ReturnValue,false,0,0,string.Empty,DataRowVersion.Default,null ));
			command.CommandType = CommandType.StoredProcedure;

			command.ExecuteNonQuery();
			userID = (int)command.Parameters["ReturnValue"].Value;

			command.Dispose();
			connection.Close();
             */
            Person p = PersonManager.LoginEmail(email, password);
            userID = (p != null) ? p.PersonId : 0;

            return (userID == 0 ? null : new CustomPrincipal(userID));
        }

		public bool IsInRole(string role)
		{
			return roleList.Contains( role );
		}

		// Properties
		public System.Security.Principal.IIdentity Identity
		{
			get { return identity; }
			set { identity = value; }
		}

		public ArrayList Roles
		{
			get { return roleList; }
		}
	}
}
